<template>
  <div class="mt-1">
    <van-button
      class="refreshstyle"
      icon="replay"
      type="default"
      @click="refreshData"
    />
    <van-form>
      <h5 class="titlestyle">
        <span style="margin: 0 0 0 0.3rem"
          >当前产区:{{ this.$store.getters.productionLine }}
        </span>
        <span style="margin: 0 0 0 1rem"> 当前配方:{{ this.FormulaName }}</span>
        <span style="margin: 0 0 0 2rem">当前上料批次:{{ this.batch }}</span>
      </h5>
      <van-field
        clearable
        v-model="FormulaCode"
        ref="pfbfocus"
        @focus="stopKeyboradFirst"
        label="投料口"
        placeholder="请扫描投料口"
      />
      <van-field
        readonly
        clearable
        v-model="FormulaNumber"
        label="配方比号"
        placeholder="配方比号"
      />
      <van-field
        v-model="code"
        clearable
        label="拍码"
        ref="pmfocus"
        @focus="stopKeyborad"
        placeholder="请输入拍码"
      />
      <ag-grid-vue
        style="width: 100%; height: 52vh"
        class="ag-theme-alpine mt-1"
        :columnDefs="columnDefs"
        :defaultColDef="defaultColDef"
        :gridOptions="gridOptions"
        :singleClickEdit="true"
        rowSelection="multiple"
        :rowData="rowData"
      >
      </ag-grid-vue>

      <van-row type="flex" gutter="10" justify="center">
        <van-col span="9">
          <van-button type="info" class="mt-1" block @click="endSubmit"
            >结束本批投料</van-button
          ></van-col
        >
        <van-col span="6">
          <van-button block type="danger" class="mt-1" @click="submit"
            >退回</van-button
          ></van-col
        >
        <van-col span="7">
          <van-button type="warning" class="mt-1" block @click="allinfo"
            >投料明细</van-button
          ></van-col
        >
      </van-row>
      <van-popup
        v-model="ShowStatue"
        position="bottom"
        style="height: 100%"
        class="bg-default"
      >
        <order-data
          :ShowDataA="ShowData"
          @get-val="SureBottom"
          v-if="ShowStatue"
        />
      </van-popup>
    </van-form>
    <OverValue
      v-model="saveValueVisible"
      @saveNum="saveNum"
      @canCel="canCel"
      :Asure="sureWIP"
      :ShowData="NumAdjustData"
    />
    <PFBData
      v-model="FBDVisible"
      :ShowDataNum="PFBData"
      @PFBNum="PFBNum"
      @PFBcancel="PFBcancel"
    />
    <InfoShow v-model="InfoVisible" :InfoData="infoData" @confirm="confirm" />
    <Printpassword
      v-model="passwordVisble"
      :em_password="em_password"
      @PasswordSuccess="PasswordSuccess"
    />
    <audio src="../../assets/warning.mp3" preload="auto" id="bgMusic"></audio>
  </div>
</template>

<script>
import { AgGrid } from "../../mixins/AgGrid";
import { mapGetters } from "vuex";
import { parseQRCode, toast } from "../../utils/common";
import { Picker } from "vant";
import { DeviceMaterial } from "../../api/feeding";
import { AgGridVue } from "ag-grid-vue";
import {
  commissionSubmit,
  EndPost,
  GetPFItem,
  OverOutStorage,
  GetPFIList,
  DeviceGive,
  SerachList,
} from "../../api/feeding";
import { pat } from "../../api/material";
import OverValue from "../../components/OverValue";
import PFBData from "../../components/PFBData.vue";
import InfoShow from "../../components/InfoShow.vue";
import Printpassword from "../../components/Printpassword.vue";
import OrderData from "../../components/OrderData.vue";

export default {
  name: "FormulaRatio",
  mixins: [AgGrid],
  data() {
    return {
      code: "",
      batch: "",
      sureWIP: "",
      em_password: "",
      passwordVisble: false,
      saveValueVisible: false,
      FBDVisible: false,
      InfoVisible: false,
      passed: true,
      ShowStatue: false,
      FormulaCode: "", //投料口
      FormulaNumber: "", //配方比号
      FormulaName: "",
      columnDefs: [
        { headerName: "物料号", field: "ProductId", width: 90 },
        { headerName: "物料名称", field: "ProductName", width: 125 },
        { headerName: "生产日期", field: "ProductionDate", width: 100 },
        {
          headerName: "数量",
          field: "Num",
          width: 70,
        },
      ],
      rowData: [],
      qrcodeResult: null,
      NumAdjustData: [], //传给数组的数据
      SKUANndformulaData: [], //配方比的物料数组
      rowPallenNoNum: [], //提交的数据
      PFBData: [],
      infoData: [],
      DeviceData: [],
      ShowData: {},
    };
  },
  components: {
    [Picker.name]: Picker,
    AgGridVue,
    OverValue,
    PFBData,
    InfoShow,
    Printpassword,
    OrderData,
  },
  computed: {
    ...mapGetters(["productionLine"]),
  },
  watch: {
    FormulaCode(val) {
      console.log(this.DeviceData);
      let result = this.DeviceData.find((it) => it.DeviceCode === val);
      if (result) {
        this.FormulaCode = val;
        this.FormulaName = result.DeviceName;
        this.SKUANndformulaData = [];
        this.SKUInfo(val);
        this.$refs.pmfocus.focus();
      } else {
        this.FormulaCode = "";
        this.FormulaName = "";
        this.FormulaNumber = "";
        this.playMusic();
        toast("没有此配方比号");
      }
      /*       if (val.length > 4 && val.length < 9) {
        this.FormulaCode = val;
        this.SKUANndformulaData = [];
        this.SKUInfo(val);
        this.$refs.pmfocus.focus();
      } else {
        this.FormulaCode = "";
        toast("请输入正确的号码");
      } */
    },
    code(val) {
      if (this.FormulaCode !== "") {
        if (val.length > 20) {
          this.qrcodeResult = parseQRCode(val);
          if (this.qrcodeResult) {
            console.log(this.qrcodeResult);
            if (this.qrcodeResult.SerialNo) {
              this.testMaterial(
                this.qrcodeResult.palletNo,
                this.qrcodeResult.materialCode,
                this.qrcodeResult.SerialNo,
                this.qrcodeResult.quantity
              );
            } else {
              this.testMaterial(
                this.qrcodeResult.palletNo,
                this.qrcodeResult.materialCode
              );
            }
          } else {
            this.playMusic();
            toast("无法识别二维码");
          }
        }
      } else {
        this.playMusic();
        toast("请先选择配方比编码");
        this.code = "";
      }
      this.code = "";
      this.$refs.pmfocus.focus();
    },
  },
  methods: {
    stopKeyboradFirst() {
      this.$refs.pfbfocus.$refs.input.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.pfbfocus.$refs.input.removeAttribute("readonly");
      }, 200);
    },
    // 消除获取焦点时自动弹出键盘
    stopKeyborad() {
      this.$refs.pmfocus.$refs.input.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.pmfocus.$refs.input.removeAttribute("readonly");
      }, 200);
    },
    //播放警示音
    playMusic() {
      setTimeout(() => {
        let audio = document.getElementById("bgMusic");
        audio.play();
      }, 200);
    },
    //获取所有的配方比号以及名称
    async DeviceNameList() {
      let res = await DeviceGive(
        "FormulaFeeding",
        this.$store.getters.productionLine
      );
      console.log(res);
      this.DeviceData = JSON.parse(JSON.stringify(res.data.Data));
    },
    //获取点击后的配方比号以及批次号
    async SKUInfo(FormulaNum) {
      let res = await DeviceMaterial(
        this.productionLine,
        "FormulaFeeding",
        FormulaNum
      );
      console.log(res);
      res.Data.SKUItems.map((it) => {
        let SKU = it.substring(0, it.indexOf(":"));
        this.SKUANndformulaData.push(SKU);
      });
      this.batch = res.Data.BatchNo;
      this.FormulaNumber = res.Data.FormulaFeedingNo;
    },
    //验证物料是否属于当前配方比，若是则提交
    async testMaterial(palletNo, materialCode, SeqNo, num) {
      if (this.SKUANndformulaData.indexOf(materialCode) !== -1) {
        //验证BQS
        let result = await pat(
          this.$store.getters.productionLine,
          palletNo,
          "U",
          this.$store.getters.WarehouseId,
          "1"
        );
        console.log(result);
        if (result.Status == 200) {
          switch (result.Data.BQSStatus) {
            case 1:
              this.em_password = result.Data.AuthPwd;
              this.passwordVisble = true;
              break;
            case 0: //投放数据
              if (this.qrcodeResult.SerialNo) {
                this.findPat(palletNo, materialCode, SeqNo, num);
              } else {
                let waterNO = undefined;
                this.findPat(palletNo, materialCode, waterNO);
              }
              this.$refs.pmfocus.focus();
              break;
            case 2:
              console.log(result);
              this.playMusic();
              toast(result.Msg);
              break;
            default:
              if (this.qrcodeResult.SerialNo) {
                this.findPat(palletNo, materialCode, SeqNo, num);
              } else {
                let waterNO = undefined;
                this.findPat(palletNo, materialCode, waterNO);
              }
              this.$refs.pmfocus.focus();
              break;
          }
        } else {
          this.playMusic();
          toast(result.Msg);
        }
      } else {
        this.playMusic();
        toast("物料号不匹配");
      }
      this.$refs.pmfocus.focus();
    },
    //密码正确
    PasswordSuccess() {
      console.log("1");
      if (this.qrcodeResult.SerialNo) {
        this.findPat(
          this.qrcodeResult.palletNo,
          this.qrcodeResult.materialCode,
          this.qrcodeResult.SerialNo,
          this.qrcodeResult.quantity
        );
      } else {
        this.findPat(
          this.qrcodeResult.palletNo,
          this.qrcodeResult.materialCode
        );
      }
    },
    //添加至表格
    async SureBottom(val, palletNo, materialCode) {
      this.ShowStatue = false;
      let user = this.$store.getters.user;
      let productionline = this.$store.getters.productionLine;
      let res = await commissionSubmit(
        productionline,
        palletNo,
        materialCode,
        "1",
        user,
        "2",
        this.FormulaCode,
        this.$store.getters.WarehouseId,
        "",
        "",
        val,
        this.batch
      );
      console.log(res);
      if (res && res.Status == 200 && res.Data) {
        this.rowData.push({
          ProductName: res.Data.ProductName,
          ProductId: res.Data.ProductId,
          UniqueId: res.Data.UniqueId,
          Num: val,
          ProductionDate: res.Data.ProductionDate.substring(0, 10),
          OutStorageBillDetailId: res.Data.OutStorageBillDetailId,
        });
        toast(res.Msg);
      } else {
        this.playMusic();
        toast(res.Msg);
      }
      this.$refs.pmfocus.focus();
    },
    //从外界添加数据
    async findPat(palletNo) {
      let productionline = this.$store.getters.productionLine;
      let res = await SerachList(
        productionline,
        palletNo,
        this.$store.getters.WarehouseId
      );
      if (res.Status == 200 && res.Data) {
        this.ShowStatue = true;
        this.ShowData = JSON.parse(JSON.stringify(res.Data));
      } else {
        this.playMusic();
        toast(res.Msg);
      }
      console.log(res);
    },
    //调数据组件
    saveNum(savevalue, sure) {
      this.savenum = savevalue;
      this.sureWIP = sure;
      this.submit();
      this.savenum = "";
      this.$refs.pmfocus.focus();
    },
    canCel(sure) {
      this.sureWIP = sure;
      this.saveValueVisible = false;
      this.savenum = "";
      this.$refs.pmfocus.focus();
    },
    PFBcancel() {
      this.$refs.pmfocus.focus();
    },
    PFBNum() {
      this.overOut();
      this.batch++;
      this.rowData = [];
      this.$refs.pmfocus.focus();
    },
    confirm() {
      this.$refs.pmfocus.focus();
    },
    //退回操作
    async submit() {
      let selectedData = this.gridApi.getSelectedRows();
      console.log(selectedData);
      if (selectedData[0]) {
        this.saveValueVisible = true;
        console.log(this.saveValueVisible);
        this.NumAdjustData.push(selectedData[0]);
        console.log(this.NumAdjustData);
        if (this.sureWIP == true) {
          let NeedDate = [
            {
              OutStorageBillDetailId: selectedData[0].OutStorageBillDetailId,
              UniqueId: selectedData[0].UniqueId,
              Num: Number(this.savenum),
            },
          ];
          let number = await EndPost(NeedDate);
          if (number.Status == 200) {
            //删除数组中的某个值
            let a = this.gridApi.updateRowData({ remove: selectedData });
            //删除rowData内此值
            let selectIndex = this.rowData.indexOf(a.remove[0]);
            this.rowData.splice(selectIndex - 1, 1);
            this.saveValueVisible = false;
            this.sureWIP = false;
            this.NumAdjustData = [];
          } else {
            this.playMusic();
            toast(number.Msg);
          }
          console.log(number);
        }
      } else {
        this.playMusic();
        toast("未选择需要退回行");
      }
      this.$refs.pmfocus.focus();
    },
    //结束本批
    async endSubmit() {
      if (
        this.FormulaCode == "" ||
        this.FormulaCode == null ||
        this.FormulaCode == undefined
      ) {
        toast("请先扫描配方比号");
      } else {
        let res = await GetPFItem(
          this.$store.getters.user,
          this.$store.getters.productionLine,
          this.FormulaCode,
          this.batch,
          "1"
        );
        console.log(res);
        if (res) {
          let _this = this;
          this.PFBData = [];
          this.FBDVisible = true;
          res.Data.map((it) => {
            _this.PFBData.push({
              bl: it.bl,
              devicecode: it.devicecode,
              maxval: it.maxval,
              num: it.num,
              numnew: it.numnew,
              productid: it.productid,
              blocknum: Math.ceil(it.num / 25),
            });
          });
          //this.PFBData = JSON.parse(JSON.stringify(res.Data));
          console.log(this.PFBData);
          /*  this.batch++;
        this.rowData = []; */
        } else {
          this.playMusic();
          toast("并未查找到数据");
        }
      }
      this.$refs.pmfocus.focus();
    },
    //信息汇总
    async allinfo() {
      if (
        this.FormulaCode == "" ||
        this.FormulaCode == null ||
        this.FormulaCode == undefined
      ) {
        this.playMusic();
        toast("请先扫描配方比号");
      } else {
        let res = await GetPFIList(
          this.$store.getters.user,
          this.$store.getters.productionLine,
          this.FormulaCode,
          this.batch,
          "1"
        );
        console.log(res);
        this.InfoVisible = true;
        this.infoData = JSON.parse(JSON.stringify(res.Data.reverse()));
        this.$refs.pmfocus.focus();
      }
    },
    //结束批次接口
    async overOut() {
      let productionline = this.$store.getters.productionLine;
      let user = this.$store.getters.user;
      let res = await OverOutStorage(
        user,
        productionline,
        this.FormulaCode,
        this.batch,
        "1"
      );
      toast(res.Msg);
      console.log(res);
      this.$refs.pmfocus.focus();
    },
    JustifyFocus() {
      if (this.FormulaCode) {
        this.$refs.pmfocus.focus();
      } else {
        this.$refs.pfbfocus.focus();
      }
    },
    //刷新按键获取新的投料口号
    refreshData() {
      this.$refs.pfbfocus.focus();
      this.DeviceNameList();
      this.SKUANndformulaData = [];
      this.SKUInfo(this.FormulaCode);
    },
  },
  mounted() {
    this.$refs.pfbfocus.focus();
    this.DeviceNameList();
  },
  activated() {
    this.JustifyFocus();
  },
};
</script>
<style scoped>
.titlestyle {
  color: gray;
  margin-top: 0.1rem;
  margin-bottom: 0.5rem;
}
.refreshstyle {
  widows: 2rem;
  height: 2rem;
  position: fixed;
  top: 0.3rem;
  right: 0.4rem;
  z-index: 99;
  background-color: white;
}
</style>